package com.binarysoft.service.map;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import com.binarysoft.service.common.multiconnpool.MultipleConnectionPoolService;
import common.framework.dsb.client.DefaultServiceFactory;
import common.framework.dsb.client.ServiceFactory;
import common.framework.log.Logger;

public abstract class AbstractDataMapDAO implements DataMapDAO {

	@Override
	public void put(String group, String key, String value) throws Exception {
		Logger.log(Logger.FUNCTION_LEVEL, "group=" + group + " key=" + key + " value=" + value);
		ServiceFactory serviceFactory = new DefaultServiceFactory();
		MultipleConnectionPoolService connectionPoolService = serviceFactory.lookup("DSB/MultipleConnectionPoolService");
		String sql = "call sp_save_data_map (?, ?, ?)";
		Connection connection = connectionPoolService.getConnection(DSB_SERVER_POOL_NAME);
		try {
			CallableStatement cstmt = connection.prepareCall(sql);
			cstmt.setString(1, group);
			cstmt.setString(2, key);
			cstmt.setString(3, value);
			cstmt.executeUpdate();
			cstmt.close();
		} finally {
			if (connection != null) {
				connection.close();
			}
		}
	}

	@Override
	public String get(String group, String key) throws Exception {
		ServiceFactory serviceFactory = new DefaultServiceFactory();
		MultipleConnectionPoolService connectionPoolService = serviceFactory.lookup("DSB/MultipleConnectionPoolService");
		String sql = "select * from data_map where map_group = ? and map_key = ?";
		Connection connection = connectionPoolService.getConnection(DSB_SERVER_POOL_NAME);
		String value = null;
		try {
			PreparedStatement pstmt = connection.prepareStatement(sql);
			pstmt.setString(1, group);
			pstmt.setString(2, key);
			ResultSet rs = pstmt.executeQuery();
			while (rs.next()) {
				value = rs.getString("map_value");
				break;
			}
			rs.close();
			pstmt.close();
		} finally {
			if (connection != null) {
				connection.close();
			}
		}
		return value;
	}

	@Override
	public void remove(String group, String key) throws Exception {
		ServiceFactory serviceFactory = new DefaultServiceFactory();
		MultipleConnectionPoolService connectionPoolService = serviceFactory.lookup("DSB/MultipleConnectionPoolService");
		String sql = "delete from data_map where map_group = ? and map_key = ?";
		Connection connection = connectionPoolService.getConnection(DSB_SERVER_POOL_NAME);
		try {
			PreparedStatement pstmt = connection.prepareStatement(sql);
			pstmt.setString(1, group);
			pstmt.setString(2, key);
			pstmt.executeUpdate();
			pstmt.close();
		} finally {
			if (connection != null) {
				connection.close();
			}
		}
	}
}
